var express = require('express');
var router = express.Router();
const fs = require("fs-extra")
const rimraf = require("rimraf")
const bodyParser = require('body-parser')
const formidable = require('express-formidable')


var connection = require('../connect');
// 加入token值验证
const jwt = require('jsonwebtoken')

const SECRET_KEY = 'JWT_SECRET_KEY'




// 视频流接口
router.get('/sumGetSize', function (req, res, next) {
  let filePath = 'public/videos/frag_bunny.mp4'
  res.set('Content-Type', 'application/octet-stream');
  fs.createReadStream(filePath).pipe(res)
})

router.get('/GetStream', function (req, res, next) {
  let filePath = 'public/videos/frag_bunny.mp4';
  const stat = fs.statSync(filePath);
  const fileSize = stat.size;
  const segmentSize = 2000000; // 每段大小，单位字节（例：1MB）
  const totalSegments = Math.ceil(fileSize / segmentSize); // 总段数
  const range = req.headers.range;

  // 返回总段数
  res.setHeader('X-Total-Segments', totalSegments);

  if (range) {
    const parts = range.replace(/bytes=/, '').split('-');
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : Math.min(start + segmentSize - 1, fileSize - 1);

    // 检查请求的范围
    if (start >= fileSize || end >= fileSize || start > end) {
      res.status(416).send('Requested range not satisfiable');
      return;
    }

    const chunksize = (end - start) + 1;
    const file = fs.createReadStream(filePath, { start, end });

    res.writeHead(206, {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    });

    file.pipe(res);
  } else {
    res.writeHead(200, {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    });
    fs.createReadStream(filePath).pipe(res);
  }
});





// 配置请求参数解析器
router.use(bodyParser.json({ extended: false }))
const filePath = "/static/"
const fileUrl = "http://localhost:3000"

router.post('/login', (req, resp) => {
  let { name, pass } = req.body;

  // 执行模糊查询
  connection.query('select * from users where admin=? and pass=?', [name, pass], (err, r) => {
    if (err) {
      resp.send({
        code: 500,
        msg: '失败'
      })
      throw err
    }
    if (r.length == 0) {
      resp.send({
        code: 1001,
        msg: '账号密码错误'
      });
    } else {
      let user = r[0]
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      let payload = { id: user.uid, nickname: user.uname }
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1d' })
      // 返回user对象与token字符串
      user.password = undefined
      // 将结果封装，返回给客户端
      resp.send({
        code: 200,
        msg: '成功',
        data: r,
        token: token
      });
    }
  }
  );
});

// 验证文件状态接口
router.post("/api/upload/verify", (req, res) => {
  // 接受前端传递参数
  let { fileMd5, extension } = req.body
  console.log(fileMd5, extension, '123')
  // 判断文件是否存在, 如果存在，秒传：返回上传成功
  if (fs.existsSync(__dirname + filePath + fileMd5 + "." + extension)) {
    res.send({
      url: fileUrl + filePath + fileMd5 + "." + extension,
      code: 200,
      uploadedList: []
    })
    return
  }
  // 如果不存在，判断是否有已经上传的切片，如果有，返回已上传切片list
  const dirPath = __dirname + filePath + fileMd5
  let files = []
  try {
    files = fs.readdirSync(dirPath);
  } catch (e) {
    // 目录不存在，使用文件的md5值为目录名创建文件
    fs.mkdirSync(dirPath)
    res.send({
      url: "",
      code: 200,
      uploadedList: []
    })
    return
  }
  res.send({
    url: "",
    code: 200,
    uploadedList: files
  })
})

// 分片上传接口
router.post("/api/upload", formidable(), (req, res) => {
  let { file } = req.files
  let { filename, fileMd5 } = req.fields
  console.log(file, filename, fileMd5)
  const newPath = __dirname + filePath + fileMd5 + "/" + filename
  console.log(newPath)
  fs.move(file.path, newPath, err => {
    if (err) {
      console.log(err)
      res.send("failed")
      return
    }
    res.send("success")
  })
})



// 合并文件接口
router.post("/api/upload/merge", async (req, res) => {
  let { fileMd5, extension } = req.body
  let files = []
  const dirPath = __dirname + filePath + fileMd5
  console.log(dirPath)
  files = fs.readdirSync(dirPath);
  console.log(files)
  files.sort((a, b) => a.split("-")[1] - b.split("-")[1])
  const fileSavePath = __dirname + filePath + fileMd5 + "." + extension
  const writeStream = fs.createWriteStream(fileSavePath)
  files.map((chunk, index) => {
    const chunkName = dirPath + "/" + fileMd5 + "-" + index
    const readStream = fs.readFileSync(chunkName)
    writeStream.write(readStream)
  })
  if (rimraf.rimrafSync(dirPath)) {
    console.log("删除目录成功")
  } else {
    console.log("删除目录失败")
  }
  res.send({
    code: 200,
    message: "上传成功"
  })
})
module.exports = router;
